package com.taiji.dicom4cloud.smart.controller;

import cn.hutool.core.util.ObjectUtil;
import com.taiji.dicom4cloud.common.core.utils.R;
import com.taiji.dicom4cloud.common.log.annotation.SnowLog;
import com.taiji.dicom4cloud.common.model.entity.SysDept;
import com.taiji.dicom4cloud.smart.model.entity.Org;
import com.taiji.dicom4cloud.smart.service.CarOwerService;
import com.taiji.dicom4cloud.smart.service.CarService;
import com.taiji.dicom4cloud.smart.service.OrgService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequiredArgsConstructor
@RequestMapping("/org" )
@Api(value = "org", tags = "组织机构")
public class OrgController {

    @Autowired
    private OrgService orgService;

    @Autowired
    private CarOwerService carOwerService;

    @Autowired
    private CarService carService;

    /**
     * 通过ID查询
     * @param id ID
     * @return SysDept
     */
    @GetMapping("/{id}")
    public R getById(@PathVariable Integer id) {
        return R.ok(orgService.getById(id));
    }

    /**
     * 返回树形菜单集合
     * @return 树形菜单
     */
    @GetMapping(value = "/tree")
    public R listDeptTrees() {
        return R.ok(orgService.listOrgTrees());
    }

    @SnowLog("添加部门")
    @PostMapping
    public R save(@Valid @RequestBody Org org) {
        return R.ok(orgService.saveOrUpdate(org));
    }

    /**
     * 删除
     * @param id ID
     * @return success/false
     */
    @SnowLog("删除部门")
    @DeleteMapping("/delOrg")
    @PreAuthorize("@pms.hasPermission('sys_dept_del')")
    public R removeById(@RequestParam("id") String id,@RequestParam("flag") String flag) {
        if(ObjectUtil.isNotEmpty(flag)){
            Org org = orgService.getById(id);
            //删除小区下的车主和车辆信息
            carOwerService.removeOwners(org.getOrgId());
            carService.removeCars(org.getOrgId());
        }
        return R.ok(orgService.removeById(id));
    }

}
